<template>
  <div class="dashboard-container">
    <div class="app-container">

      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>活动管理</el-breadcrumb-item>
        <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片区域 -->
      <el-card class="box-card">
        <!-- 搜索与添加 -->
        <el-row :gutter="20">
          <!-- 搜索框 -->
          <el-col :span="8">
            <el-input v-model="userInfo.query" placeholder="请输入内容" clearable @clear="loadUserList">
              <el-button slot="append" icon="el-icon-search" @click="loadUserList" />
            </el-input>
          </el-col>
          <!-- 添加按钮 -->
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 表格 -->
        <el-table
          :data="userList"
          border
          style="width: 100%"
          stripe
        >
          <el-table-column type="index" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="mobile" label="电话" />
          <el-table-column prop="role_name" label="角色" />
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userStateChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <!-- 修改 -->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              />
              <!-- 删除 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="removeUserById(scope.row.id)"
              />
              <!-- 分配角色 -->
              <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          :current-page="userInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="userInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>

      <!-- 添加用户的对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 主体内容 表单 -->
        <el-form ref="ruleForm" :model="addForm" :rules="addFormRules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username" />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email" />
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile" />
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户的对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
      >
        <el-form ref="editForm" :model="editForm" :rules="editFormRules" label-width="100px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile" />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUserList, putUserState, addNewUser, getUserInfoById, editUserInfoById, removeUserInfoById } from '@/api/user.js'
export default {
  data() {
    return {
      // 获取用户列表的参数
      userInfo: {
        query: '',
        pagenum: 1, // 当前的页数
        pagesize: 2
      },
      // 用户列表数据
      userList: [],
      total: null,
      addDialogVisible: false, // 控制添加用户对话框的显示与隐藏
      addForm: { // 添加用户的数据对象
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      },
      editDialogVisible: false, // 控制修改用户对话框的显示与隐藏
      editForm: {}, // 修改用户信息的对象数据
      // 修改用户表单校验规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
        ]
      }
    }
  },

  created() {
    this.loadUserList()
  },

  methods: {
    // 加载用户列表
    async loadUserList() {
      try {
        const res = await getUserList(this.userInfo)
        // console.log(res, '用户列表')
        this.userList = res.users
        this.total = res.total
      } catch (err) {
        this.$message.error('获取用户列表失败')
      }
    },
    // 分页 选择每一页数量size
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.userInfo.pagesize = newSize
      this.loadUserList()
    },
    // 分页 选择当前页page
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.userInfo.pagenum = newPage
      this.loadUserList()
    },
    // 用户状态
    async userStateChange(e) {
      try {
        await putUserState(e.id, e.mg_state)
        this.$message.success('更新用户状态成功')
      } catch (err) {
        this.e.mg_state = !e.mg_state // 更新失败的话，要将页面状态还原
        this.$message.error('更新用户状态失败')
      }
    },
    // 监听表单关闭事件
    addDialogClosed() {
      this.$refs.ruleForm.resetFields() // 清空表单数据 组件提供.resetFields()
    },
    // 点击确定 添加用户
    addUser() {
      this.$refs.ruleForm.validate(async(valid) => { // valid是一个布尔值，代表校验结果
        // console.log(valid)
        if (!valid) return // 如果校验不通过，则直接return，不执行后面的代码
        // console.log('校验通过')
        try {
          await addNewUser(this.addForm)
          this.addDialogVisible = false // 关闭添加用户的对话框
          this.$message.success('添加用户成功!')
          // console.log(777)
          this.loadUserList() // 重新渲染用户列表
        } catch (err) {
          console.dir(err)
          this.$message.error('添加用户失败!')
        }
      })
    },
    // 点击修改按钮
    async showEditDialog(id) {
      this.editDialogVisible = true // 展示修改用户信息对话框
      // console.log(id) // 通过作用域插槽拿到 用户id
      try {
        const res = await getUserInfoById(id)
        // console.log(res)
        this.editForm = res
      } catch (err) {
        this.$message.error('网络繁忙')
      }
    },
    // 点击确定 修改用户
    editUserInfo() {
      this.$refs.editForm.validate(async(valid) => {
        // console.log(valid)
        if (!valid) return
        try {
          await editUserInfoById(this.editForm.id, this.editForm.email, this.editForm.mobile)
          this.editDialogVisible = false
          this.loadUserList() // 重新渲染用户列表
          this.$message.success('修改用户信息成功')
        } catch (err) {
          this.$message.error('修改用户信息失败')
        }
      })
    },
    // 点击删除按钮
    async removeUserById(id) {
      // console.log(id)
      // 询问弹框
      // 返回值是一个promise对象，所以可以用async await
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err // 捕获错误以后再return返还给res
      })
      // console.log(res) // 确认confirm  取消cancel
      if (res !== 'confirm') {
        this.$message('已取消删除')
        return // 点击取消代表什么也不用做 直接return掉
      }
      try {
        await removeUserInfoById(id)
        this.editDialogVisible = false
        this.loadUserList() // 重新渲染用户列表
        this.$message.success('删除成功!')
      } catch (err) {
        this.$message.error('网络繁忙')
        this.editDialogVisible = false
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.el-breadcrumb {
  margin-bottom: 15px;
}
.el-table {
  margin-top: 15px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
